"""
<name>Initial Population</name>
<description>Initial Population</description>
<contact>Leidy Garzon</contact>
<icon>icons/InitPop.svg</icon>
<priority>1040</priority>

"""
from Goldenberry.widgets import *
from OWItemModels import PyListModel
import OWGUI, OWGUIEx
from OWWidget import *

class GbInitPopWidget(OWWidget):
    """Widget for initial population setup"""
    seeds = []
    seed_index = []
    new_seed = ""
    bias = []
    new_subspace_min = ""
    new_subspace_max = ""
    new_subspace_mu = ""
    new_subspace_sigma = ""
    new_perctg_pop_bias = ""
    type = "Random"
    params = None

    def __init__(self, parent=None, signalManager=None):
        OWWidget.__init__(self, parent,signalManager, title='Initial Population')
        self.recentFiles = []
        self.setup_interfaces()
        self.setup_ui()
              
    def setup_interfaces(self):
        self.outputs = [("Initial Pop", InitPop)]

    def setup_ui(self):
        load_widget_ui(self)
        
        #Seeds UI
        self.seedBox.setLayout(QFormLayout(self.seedBox))
        seed_box = OWGUI.widgetBox(self.controlArea,orientation=0)
        seed_line = OWGUI.lineEdit(seed_box, self, "new_seed")
        add_seed_btn = OWGUI.toolButton(seed_box, self, "+", self.add_seed, tooltip = "Add seed individual", width=20, height=20)
        del_seed_btn = OWGUI.toolButton(seed_box, self, "-", self.delete_seed, tooltip = "Delete selected individual", width=20, height=20)
        browse_btn = OWGUI.button(self, self, 'Browse to load seeds from file', callback=self.browse_file)
        browse_btn.setIcon(self.style().standardIcon(QStyle.SP_DirOpenIcon))
        self.seeds_list = QListWidget(self)
        self.seedBox.layout().addRow(seed_box)
        self.seedBox.layout().addRow(self.seeds_list)
        self.seedBox.layout().addRow(browse_btn)
        OWGUI.widgetLabel(self.seedBox,'<html><head/><body><p align="justify"><span style=" font-size:7pt; font-weight:600;">Instructions</span><span style=" font-size:7pt;">:<br/>Register </span><span style=" font-size:7pt; font-weight:600;">seed individuals</span><span style=" font-size:7pt;"> separing each position by a comma and <br/>pressing the </span><span style=" font-size:7pt; font-style:italic;">add</span><span style=" font-size:7pt;"> button or loading a </span><span style=" font-size:7pt; font-style:italic;">csv</span><span style=" font-size:7pt;"> file containing individuals, </span><a name="result_box"/><span style=" font-size:7pt;">e</span><span style=" font-size:7pt;">ach <br/>individual must be on one line of the file.<br/>Remove inserted </span><span style=" font-size:7pt; font-weight:600;">seedindividuals</span><span style=" font-size:7pt;"> by selecting the individual from the <br/>list and pressing the </span><span style=" font-size:7pt; font-style:italic;">less </span><span style=" font-size:7pt;">button</span></p></body></html>')
        #self.seedBox.layout().addRow(a)

        #Bias UI
        self.biasBox.setLayout(QFormLayout(self.biasBox))
        bias_box = OWGUI.widgetBox(self.controlArea,orientation=0)
        #mu_line = OWGUI.lineEdit(bias_box, self, "new_subspace_min", label="min:", valueType = float, validator = QDoubleValidator(0.0, 1.0, 4, self.controlArea))
        min_line = OWGUI.lineEdit(bias_box, self, "new_subspace_min", label="min:",valueType = float)
        max_line = OWGUI.lineEdit(bias_box, self, "new_subspace_max", label="max:",valueType = float)
        mu_line = OWGUI.lineEdit(bias_box, self, "new_subspace_mu", label= QChar(0x03BC),valueType = float)
        sigma_line = OWGUI.lineEdit(bias_box, self, "new_subspace_sigma", label= QChar(0x03C3),valueType = float)
        perctg_line = OWGUI.lineEdit(bias_box, self, "new_perctg_pop_bias", label="%:",valueType = float)
        add_bias_btn = OWGUI.toolButton(bias_box, self, "+", self.add_subspace, tooltip = "Add subspace", width=20, height=20)
        del_bias_btn = OWGUI.toolButton(bias_box, self, "-", self.delete_subspace, tooltip = "Delete selected subspace", width=20, height=20)
        #perctg_line = OWGUI.lineEdit(self, self, "new_perctg_pop_bias", label="Percentage of population to bias (%):", valueType = float, validator = QDoubleValidator(0.0, 100.0, 4, self.controlArea))
        self.bias_list = QListWidget(self)
        self.biasBox.layout().addRow(bias_box)
        self.biasBox.layout().addRow(self.bias_list)
        OWGUI.widgetLabel(self.biasBox,'<html><head/><body><p align="justify"><span style=" font-size:7pt; font-weight:600;">Instructions</span><span style=" font-size:7pt;">:<br/>Define each </span><span style=" font-size:7pt; font-weight:600;">search subspace</span><span style=" font-size:7pt;"> by </span><a name="result_box"/><span style=" font-size:7pt;">s</span><span style=" font-size:7pt;">pecifying the</span><span style=" font-size:7pt; font-style:italic;"> range max</span><span style=" font-size:7pt;">,</span><span style=" font-size:7pt; font-style:italic;"> range min</span><span style=" font-size:7pt;">, </span><span style=" font-size:7pt; font-style:italic;"><br/>mu</span><span style=" font-size:7pt;">, and </span><span style=" font-size:7pt; font-style:italic;">sigma, </span><span style=" font-size:7pt;">and percentage of population to bias and pressing the </span><span style=" font-size:7pt; font-style:italic;">add<br/></span><span style=" font-size:7pt;"> button.<br/>Remove inserted </span><span style=" font-size:7pt; font-weight:600;">search subspace</span><span style=" font-size:7pt;"> by selecting the subspace from the <br/>list and pressing the </span><span style=" font-size:7pt; font-style:italic;">less </span><span style=" font-size:7pt;">button<br/></span></p></body></html>')
        #self.biasBox.layout().addRow(perctg_line.box, perctg_line)
        # TODO: pasar por parametro y llamar a un solo metodo
        # Subscribe signals
        QObject.connect(self.random_rad_btn,QtCore.SIGNAL("clicked()"), self.random_selected)
        QObject.connect(self.seed_rad_btn,QtCore.SIGNAL("clicked()"), self.seed_selected)
        QObject.connect(self.bias_rad_btn,QtCore.SIGNAL("clicked()"), self.bias_selected)
        QObject.connect(self.applyButton,QtCore.SIGNAL("clicked()"), self.apply)
        
    def browse_file(self, startpath=None):
        startpath = os.path.expanduser("~/")
        filename = QFileDialog.getOpenFileName(self, 'Open Orange Data File', startpath)
        filename = unicode(filename)
        
    def random_selected(self):
        self.type = "Random"
        self.seedBox.setEnabled(False)
        self.biasBox.setEnabled(False)

    def seed_selected(self):
        self.type = "Reeded"
        self.seedBox.setEnabled(True)
        self.biasBox.setEnabled(False)

    def bias_selected(self):
        self.type = "Biased"
        self.seedBox.setEnabled(False)
        self.biasBox.setEnabled(True)
        """elif int(id)==2:
            self.random_rad_btn.setEnabled(True)
        elif int(id)==2:
            self.seed_rad_btn.setEnabled(True)
        else:
            self.bias_rad_btn.setEnabled(True)"""

    def add_seed(self):
        if(self.new_seed!=""):
            self.seeds_list.addItem(self.new_seed)
            self.seeds.append(GbIndividual(params = np.fromstring(self.new_seed, sep=',')))
            self.new_seed=""
                
    def delete_seed(self):
        self.seeds_list.takeItem(self.seeds_list.currentRow())
        del self.seeds[self.seeds_list.currentRow()]

    def add_subspace(self):    
        if(self.new_subspace_min!="" and self.new_subspace_max!="" and
              self.new_subspace_mu!="" and self.new_subspace_sigma!="" ):
            self.bias_list.addItem("["+str(self.new_subspace_min) + ", " + str(self.new_subspace_max) + ", " + str(self.new_subspace_mu) + ", " + str(self.new_subspace_sigma) + ", " + str(self.new_perctg_pop_bias)+ "]")
            self.bias.append(dict(mu=self.new_subspace_mu, sigma=self.new_subspace_sigma, range_min=self.new_subspace_min, range_max=self.new_subspace_max, perc=self.new_perctg_pop_bias))
            self.new_subspace_min = self.new_subspace_max= self.new_subspace_mu= self.new_subspace_sigma= self.new_perctg_pop_bias="" 
                        
    def delete_subspace(self):
        self.bias_list.takeItem(self.bias_list.currentRow())
        del self.bias[self.bias_list.currentRow()]

    def apply(self):
        init_pop = InitPop()
        init_pop.set_params(params = self.built_params(self.type))
        init_pop.set_type(type = self.type)
        self.accept()
        self.send("Initial Pop", init_pop)

    def built_params(self, type):
        if(type=="biased"):
          return self.bias
        elif(type=="seeded"):
          return self.seeds
        else:
          return None

    if __name__=="__main__":
        test_widget()

    def test_widget():
        app = QApplication(sys.argv)
        w = GbInitPopWidget()
        w.show()
        app.exec_()
